package com.controller;

import com.model.*;
import com.response.Response;
import com.service.*;
import com.util.PageBean;
import com.util.removeHTML;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/api/works")
public class WorksController{

	@Resource
	private WorksService worksService;

	@Resource
	private StudentsService studentsService;

	@Resource
	private RecordsService recordsService;

	@Resource
	private PhotosService photosService;


	//任务列表
	@RequestMapping(value="/list")
	@CrossOrigin
	public Response<List<Works>> list(@RequestBody Works works, @RequestParam Integer currentPage,
			HttpServletRequest req) throws Exception {
		int pageSize = Integer.parseInt(req.getParameter("pageSize")); //每页显示记录数
		int offset = (currentPage - 1) * pageSize; //当前页开始记录
		int counts = 0; //总记录数
		PageBean page = new PageBean(offset, pageSize); //分页对象
		//查询记录总数
		counts = worksService.getCount(works);
		//获取当前页记录
		List<Works> worksList = worksService.queryWorksList(works, page);

		int page_count = counts % PageBean.PAGE_IETM == 0 ? counts / PageBean.PAGE_IETM
				: counts / PageBean.PAGE_IETM + 1; //总页数
		return Response.success(worksList, counts, page_count);
	}

	// 任务列表
	@RequestMapping(value = "/list2")
	@CrossOrigin
	public Response<List<Works>> list2( Works works, @RequestParam Integer currentPage,
			HttpServletRequest req) throws Exception {
		int pageSize = Integer.parseInt(req.getParameter("pageSize")); // 每页显示记录数
		int offset = (currentPage - 1) * pageSize; // 当前页开始记录
		int counts = 0; // 总记录数
		PageBean page = new PageBean(offset, pageSize); // 分页对象
		// 查询记录总数
		counts = worksService.getCount(works);
		// 获取当前页记录
		List<Works> worksList = worksService.queryWorksList(works, page);

		int page_count = counts % PageBean.PAGE_IETM == 0 ? counts / PageBean.PAGE_IETM
				: counts / PageBean.PAGE_IETM + 1; // 总页数
		return Response.success(worksList, counts, page_count);
	}

	//添加任务
	@ResponseBody
	@PostMapping(value = "/add")
	@CrossOrigin
	public Response add(HttpServletRequest req) throws Exception {
		try {
			// 从请求参数中获取数据
			String sno = req.getParameter("sno");
			String wtitle = req.getParameter("wtitle");
			String wdate = req.getParameter("wdate");
			String address = req.getParameter("address");
			String wmemo = req.getParameter("wmemo");
			String wprice = req.getParameter("wprice");
			String tid = req.getParameter("tid");
			String lo = req.getParameter("lo");
			String la = req.getParameter("la");
			String photo = req.getParameter("photo");

			// 创建Works对象
			Works works = new Works();
			works.setSno(sno);
			works.setWtitle(wtitle);
			works.setWdate(wdate);
			works.setAddress(address);
			works.setWmemo(wmemo);
			works.setWprice(wprice);
			works.setTid(Integer.parseInt(tid));
			works.setLo(lo);
			works.setLa(la);

			// 设置当前时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String currentTime = sdf.format(new Date());

			Students students = studentsService.queryStudentsById(sno);

			// 判断账户余额是否充足
			if (Double.parseDouble(students.getUval().toString()) >= Double.parseDouble(works.getWprice().toString())) {
				works.setFlag("待接单");
				worksService.insertWorks(works);

				// 扣除账户余额
				double newBalance = Double.parseDouble(students.getUval().toString()) - Double.parseDouble(works.getWprice().toString());
				students.setUval(String.valueOf(newBalance));
				studentsService.updateStudents(students);

				// 添加记录
				Records records = new Records();
				records.setSno(works.getSno());
				records.setRtype("支出");
				// Set money amount as string
				records.setRtime(currentTime);
				records.setRmemo("发布任务扣除佣金：" + works.getWprice() + "元");
				recordsService.insertRecords(records);

				Integer wid = 0;
				List<Works> worksList = worksService.queryWorksList(works, new PageBean(0, 1));
				if (worksList != null && worksList.size() > 0) {
					wid = worksList.get(0).getWid();
				}

				if (photo != null && !photo.equals("")) {
					String[] photoList = photo.split(",");
					for (int i = 0; i < photoList.length; i++) {
						Photos photos = new Photos();
						photos.setWid(wid);
						photos.setAddr(photoList[i]);
						photosService.insertPhotos(photos);
					}
				}
				return Response.success();
			}
			else
			{
				return Response.error(201, "账户余额不足");
			}

		} catch (Exception e) {
			e.printStackTrace();
			return Response.error(500, "服务器错误: " + e.getMessage());
		}
	}

	//删除任务
	@ResponseBody
	@PostMapping(value = "/del")
	@CrossOrigin
	public Response del(HttpServletRequest req) throws Exception {
		try {
			int id = Integer.parseInt(req.getParameter("id"));
			worksService.deleteWorks(id); //删除
			} catch (Exception e) {
			return Response.error();
		}
		return Response.success();
	}

	//修改任务
	@ResponseBody
	@PostMapping(value = "/update")
	@CrossOrigin
	public Response update(@RequestBody Works works, HttpServletRequest req) throws Exception {
		try {
			worksService.updateWorks(works); //修改
		} catch (Exception e) {
			return Response.error();
		}
		return Response.success();
	}

	// 修改任务
	@ResponseBody
	@PostMapping(value = "/update2")
	@CrossOrigin
	public Response update2( Works works, HttpServletRequest req) throws Exception {
		try {
			worksService.updateWorks(works); // 修改
		} catch (Exception e) {
			return Response.error();
		}
		return Response.success();
	}

	//返回任务详情
	@ResponseBody
	@PostMapping(value = "/get")
	@CrossOrigin
	public Response get(HttpServletRequest req) throws Exception {
		try {
			int id = Integer.parseInt(req.getParameter("id"));
			Works works=worksService.queryWorksById(id); //根据ID查询
			return Response.success(works);
			} catch (Exception e) {
			return Response.error();
		}

	}

}

